package com.neu.flashmall.user.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.neu.common.constant.RedisRegion;
import com.neu.flashmall.user.entity.UmsAddress;
import com.neu.flashmall.user.entity.UmsUser;
import com.neu.flashmall.user.mapper.UmsAddressMapper;
import com.neu.flashmall.user.mapper.UmsUserMapper;
import com.neu.flashmall.user.service.UmsUserService;
import com.neu.flashmall.user.utils.UmsRedisKeyUtil;
import com.neu.flashmall.user.vo.UserVo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UmsUserServiceImpl implements UmsUserService {
    @Resource
    private UmsUserMapper umsUserMapper;
    @Resource
    private UmsAddressMapper umsAddressMapper;

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public List<UmsUser> selectAll() {
        return umsUserMapper.selectAll();
    }

    @Override
    public UmsUser getOne(Long id) {
        return umsUserMapper.selectByPrimaryKey(id);
    }

    @Override
    public int delete(long id) {
        return umsUserMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Long insert(UmsUser umsUser) {
        Date date = new Date();
        umsUser.setCreateTime(date);
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(umsUser.getPassword());
        umsUser.setPassword(encode);
        this.umsUserMapper.insert(umsUser);
        return umsUser.getId();
    }

    @Override
    public int update(UmsUser umsUser) {
        return umsUserMapper.updateByPrimaryKeySelective(umsUser);
    }

    @Override
    public boolean checkUmsUserName(UmsUser umsUser) {
        UmsUser user = umsUserMapper.selectByName(umsUser.getUsername());
        if(user == null){
            return true;
        }else{
            if(user.getId() == umsUser.getId()){
                return true;
            }
        }
        return false;
    }

    @Override
    public String usePhoneLogin(String phone) {
        UmsUser umsUser = umsUserMapper.selectByPhone(phone);
        if(umsUser == null){
            Date date = new Date();
            UmsUser user = new UmsUser();
            user.setCreateTime(date);
            user.setUsername(phone);
            user.setPhone(phone);
            user.setNickname("-");
            user.setCity("-");
            user.setJob("-");
            user.setSign("-");
            user.setBirth(new Date());
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            String encode = passwordEncoder.encode("123456");
            user.setPassword(encode);

            umsUserMapper.insert(user);
            return "注册成功";
        }
        return "手机号已被注册,忘记密码联系管理员";

    }

    @Override
    public String useAccountLogin(String username, String password) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        UmsUser umsUser = umsUserMapper.selectByUsername(username);
        if(username == null){
            return "该用户不存在";
        }
        boolean result = passwordEncoder.matches(password,umsUser.getPassword());
        if(result){
            return "登陆成功";
        }
        return "账户名或密码错误";
    }

    @Override
    public String saveCart(Long id, String cartJSON) {
        String key = RedisRegion.FLASH_MALL_USER_REGION + "::" + UmsRedisKeyUtil.USER_CART + id;
        redisTemplate.opsForValue().set(key,cartJSON);
        return "ok";
    }

    @Override
    public String getCart(Long id) {
        String key = RedisRegion.FLASH_MALL_USER_REGION + "::" + UmsRedisKeyUtil.USER_CART + id;
        String JSON = (String) redisTemplate.opsForValue().get(key);
        return JSON;
    }

    @Override
    public List<UmsAddress> getUserAddresses(Long userId) {
        return umsAddressMapper.getUserAddresses(userId);
    }

    @Override
    public UserVo login(String username, String password) {
        UmsUser umsUser = umsUserMapper.selectByName(username);
        if(umsUser == null) return null;
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        boolean result = encoder.matches(password,umsUser.getPassword());
        if(!result) return null;
        UserVo userVo = new UserVo();
        userVo.setDetail(umsUser);
        userVo.setToken(getUserToken(umsUser.getId()));
        return userVo;
    }

    private String getUserToken(Long userId){
        if(userId == null) throw new NullPointerException();
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(UmsRedisKeyUtil.generateKey(token),userId,1, TimeUnit.DAYS);
        return token;
    }

    @Override
    public PageInfo<UmsUser> getPaged(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<UmsUser> list = umsUserMapper.selectAll();
        PageInfo<UmsUser> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }
}
